import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthInterCeptor extends Interceptor {
  // AuthInterCeptor();

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    //在此处添加不需要token的终端链接
    final listOfPaths = <String>['/send-top', '/validate-otp'];
    //在此处添加不需要token的终端链接
    //
    // 检查如果请求端点匹配
    if (listOfPaths.contains(options.path.toString())) {
      // 如果端点匹配然后跳到追加令牌
      return handler.next(options);
    }
    //
    // 在这里加载令牌到 header
    var token = '';
    SharedPreferences sPref = await SharedPreferences.getInstance();
    if (sPref.getString("token") != null) {
      token = sPref.getString("token")!;
    }
    options.headers.addAll({'Authorization': token});
    return handler.next(options);
  }

  // 你也可以在响应或错误时执行一些动作
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    return handler.next(response);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    return handler.next(err);
  }
}
